package com.zhangxx.web.common.handler;

import com.zhangxx.web.common.exception.BusinessException;
import com.zhangxx.web.common.exception.IllegalRequestException;
import com.zhangxx.web.common.model.ResponseMessage;
import com.zhangxx.web.common.model.ServerStatus;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.Set;

/**
 * @Description:框架全局处理，异常、校验以及controller的全局返回 拦截用requestmapping注解的方法
 */
@RestControllerAdvice
public class GlobeControllerHandler {

    private Logger log = LoggerFactory.getLogger(GlobeControllerHandler.class);

    /**
     * @param request
     * @param response
     * @param be
     * @return
     * @Description 对系统内所有抛出的业务类异常进行处理
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseMessage<String> catchControllerException(HttpServletRequest request, HttpServletResponse response, BusinessException be) {
        ResponseEntity<String> a =new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);

        return new ResponseMessage<String>(be.getCode(), be.getMessage(), null);
    }

    /**
     * @param request
     * @param ex
     * @return
     * @Description 对非法请求异常进行处理
     */
    @ExceptionHandler(IllegalRequestException.class)
    @ResponseBody
    public ResponseMessage<String> catchIllegalRequestExceptionException(HttpServletRequest request, Throwable ex) {
        return new ResponseMessage<String>(ServerStatus.ILLEGAL_REQUEST.value(), ex.getMessage(), null);
    }

    /**
     * @param request
     * @param ex
     * @return
     * @Description 对exception异常进行处理
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> catchSystemException(HttpServletRequest request, Throwable ex) {
        log.error("ErrorMessage:" + ExceptionUtils.getStackTrace(ex));
        return new ResponseEntity<String>("服务异常,请稍后再试",HttpStatus.INTERNAL_SERVER_ERROR);

    }


}
